import express from "express";
import dbhelp from "./../../lib/dahelper";
import async from 'async';
import path from "path";
import fs from "fs";
let adminRouter = express.Router();
adminRouter.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By", ' 3.2.1')
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
})


adminRouter.post("/uploadImage", (request, response, next) => {
    //     uploadImage:function (req,res) {
        // let form = new formidable.IncomingForm();
        // console.log("request",request.files[0]);
        const url=path.join(__dirname+"./../../public/upload/");
fs.readdir(url, 'utf8', (err, fileList) => {
    // console.log(fileList);
    if (err) {
        console.log(err);
    }
    fileList.forEach((item,index)=>{
         let length = item.split('.').length;
         if(length==1)
         {
           console.log(item);
              let newName = item+".png";
         let oldName = item;
        // console.log(url);
        fs.rename(url+oldName,url+newName,(err)=>{
           console.log(err);
        });
         }    
    })
})
response.json({
            data:request.files[0].filename
        })
})


adminRouter.post("/login", (request, response, next) => {
  let msglogin_sql = "SELECT * FROM admin WHERE a_name=? AND a_pwd=?";
  let params = [request.body.a_name, request.body.a_pwd];
//   console.log(params)
  dbhelp.query(msglogin_sql, params, (err, reslut) => {
    if (err) {
      response.json({
        err
      })
    } else {
      if (reslut.length >= 1) {
        response.json({
          msg: "登陆成功",
          status: 1
        })
      } else {
        response.json({
          msg: "用户名或密码不正确",
          status: -1
        })
      }
    }
  })
})
adminRouter.post("/usermsg",(request,response,next)=>
{
   let size = request.body.limit * 1 // 页大小
   console.log(request.body.limit);
   let start = (request.body.page - 1) * request.body.limit; 
   let params=[start,size]
   console.log(params);
      function fn1(cb)
      {
         let getusersql="SELECT u_name,u_sex,u_age,u_status,u_email,u_number,u_address FROM user"
         
         console.log(request.body)
         if(request.body.name)
         {
            params.unshift(request.body.name);
            console.log(params)
            getusersql += " WHERE LOCATE(?, `u_name`)"
         }
         getusersql+=" LIMIT ?,? ;"
         console.log(getusersql);
         dbhelp.query(getusersql,params,(err,reslut)=>{
          console.log(getusersql);
            cb(err,reslut);
         }
         )
      }
      function fn2(cb)
      {
         let sqlcount="SELECT COUNT(*) AS count1  FROM user";
         let params=[];
         if(request.body.name)
         {
            params.unshift(request.body.name);
            sqlcount += " WHERE LOCATE(?, `u_name`) ";
         }
         dbhelp.query(sqlcount,params,(err,result)=>
         {
            cb(err,result);
         })
      }

      setTimeout(()=>
      {
         async.parallel([fn1,fn2],(err,val)=>
         {
           console.log(val);
            let resultObj = {
               "code": 0,
               "msg": "",
               "count": val[1][0]["count1"],
               data: val[0]
           }
           response.json(resultObj);
         })
      
      },1000)
})
adminRouter.post("/deluser",(request,response,next)=>
{
  // console.log(JSON.stringify(request.body.names))
  // console.log(typeof(Array.from(request.body.names)))
  let u_name=JSON.stringify(request.body.names)
  u_name=u_name.substring(1,u_name.length-1);
   u_name=u_name.split(',');
  // console.log(u_name)
  let count=u_name.length;
  let arr=""
  for(let i=0;i<count;i++)
  {
    arr+=",?"
  }
  arr=arr.substring(1)
  let delusersql=`DELETE FROM USER WHERE u_name IN (${arr})`;
  console.log(delusersql)

  dbhelp.query(delusersql,u_name,(err,result)=>
  {
    if(err)
    {
      response.json({
        err
      })
    }
    else{
      if(result.affectedRows>=1)
      {
        response.json({
          msg:"删除成功",
          status:1
        })
      }
      else{
        response.json({
          msg:"删除失败",
          status:-1
        })
      }
    }
  })
})


adminRouter.post("/delgoods",(request,response,next)=>
{
  // console.log(JSON.stringify(request.body.names))
  // console.log(typeof(Array.from(request.body.names)))
  let p_id=JSON.stringify(request.body.p_id)
  p_id=p_id.substring(1,p_id.length-1);
   p_id=p_id.split(',');
  // console.log(u_name)
  let count=p_id.length;
  let arr=""
  for(let i=0;i<count;i++)
  {
    arr+=",?"
  }
  arr=arr.substring(1)
  let delgoodssql=`DELETE FROM hs_product WHERE p_id IN (${arr})`;
  console.log(delgoodssql)

  dbhelp.query(delgoodssql,p_id,(err,result)=>
  {
    if(err)
    {
      response.json({
        err
      })
    }
    else{
      if(result.affectedRows>=1)
      {
        response.json({
          msg:"删除成功",
          status:1
        })
      }
      else{
        response.json({
          msg:"删除失败",
          status:-1
        })
      }
    }
  })
})

adminRouter.post("/logins", (request, response, next) => {
  let msglogin_sql = "SELECT * FROM USER WHERE (u_name=? OR u_email=?) AND u_password=?";
  let params = [request.body.u_name,request.body.u_name, request.body.u_pwd];
  // console.log(params)
  dbhelp.query(msglogin_sql, params, (err, reslut) => {
    console.log(reslut)
    if (err) {
      response.json({
        err
      })
    } else {
      // console.log(reslut[0].u_img)
      if (reslut.length >= 1) {
        response.json({
          msg: "登陆成功",
          status: 1,
          img:reslut[0]
        })
      } else {
        response.json({
          msg: "用户名或密码不正确",
          status: -1
        })
      }
    }
  })
})

adminRouter.post("/productmsg",(request,response,next)=>
{
   let size = request.body.limit * 1 // 页大小
   console.log(request.body.limit);
   let start = (request.body.page - 1) * request.body.limit; 
   let params=[start,size]
   console.log(params);
      function fn1(cb)
      {
         let getusersql="SELECT p_id,p_img,p_name,p_price,hs_id,p_detailes,p_stock,p_company,p_recommend FROM `hs_product`"
         
         console.log(request.body)
         if(request.body.name)
         {
            params.unshift(request.body.name);
            console.log(params)
            getusersql += " WHERE LOCATE(?, `p_name`)"
         }
         getusersql+=" LIMIT ?,? ;"
         console.log(getusersql);
         dbhelp.query(getusersql,params,(err,reslut)=>{
          console.log(getusersql);
            cb(err,reslut);
         }
         )
      }
      function fn2(cb)
      {
         let sqlcount="SELECT COUNT(*) AS count1  FROM hs_product";
         let params=[];
         if(request.body.name)
         {
            params.unshift(request.body.name);
            sqlcount += " WHERE LOCATE(?, `p_name`) ";
         }
         dbhelp.query(sqlcount,params,(err,result)=>
         {
            cb(err,result);
         })
      }

      setTimeout(()=>
      {
         async.parallel([fn1,fn2],(err,val)=>
         {
           console.log(val);
            let resultObj = {
               "code": 0,
               "msg": "",
               "count": val[1][0]["count1"],
               data: val[0]
           }
           response.json(resultObj);
         })
      
      },1000)
})

adminRouter.post("/crowdmsg",(request,response,next)=>
{
   let size = request.body.limit * 1 // 页大小
   console.log(request.body.limit);
   let start = (request.body.page - 1) * request.body.limit; 
   let params=[start,size]
   console.log(params);
      function fn1(cb)
      {
         let getusersql="SELECT * FROM `crowd_product` where c_status=0"
         
        //  console.log(request.body)
         if(request.body.name)
         {
            params.unshift(request.body.name);
            // console.log(params)
            getusersql += " and LOCATE(?, `c_name`)"
         }
         getusersql+=" LIMIT ?,? ;"
        //  console.log(getusersql);
         dbhelp.query(getusersql,params,(err,reslut)=>{
          // console.log(getusersql);
            cb(err,reslut);
         }
         )
      }
      function fn2(cb)
      {
         let sqlcount="SELECT COUNT(*) AS count1  FROM crowd_product where c_status=0";
         let params=[];
         if(request.body.name)
         {
            params.unshift(request.body.name);
            sqlcount += " and LOCATE(?, `c_name`) ";
         }
        //  console.log(sqlcount)
         
         dbhelp.query(sqlcount,params,(err,result)=>
         {
            cb(err,result);
         })
      }
      function fn3(cb)
      {
        // console.log(request.body.data)
        let params1=[parseInt(request.body.data),start,size]
         let newcrowdsql="SELECT * FROM `crowd_product` where c_status=1 and CAST(startday AS SIGNED INTEGER)>? LIMIT ?,?"
         
         dbhelp.query(newcrowdsql,params1,(err,reslut)=>{
            cb(err,reslut);
         }
         )
      }
      function fn4(cb)
      {
        let params2=[parseInt(request.body.data),parseInt(request.body.data),start,size]
        console.log("params2",params2)
        let suoyousql="SELECT * FROM `crowd_product` where c_status=1 and UNIX_TIMESTAMP(c_day)*1000>? and CAST(startday AS SIGNED INTEGER)<? LIMIT ?,?";
        dbhelp.query(suoyousql,params2,(err,reslut)=>{
          console.log("zhongchouzhong",reslut)
          cb(err,reslut);
       })
      }
      function fn5(cb)
      {
        let params2=[parseInt(request.body.data),start,size]
        let suoyousql="SELECT * FROM `crowd_product` where c_status=1 and UNIX_TIMESTAMP(c_day)*1000<? and c_arrive>=c_targetmoney LIMIT ?,?";
        dbhelp.query(suoyousql,params2,(err,reslut)=>{
          cb(err,reslut);
       })
      }
      function fn6(cb)
      {
        let params2=[parseInt(request.body.data),start,size]
        let suoyousql="SELECT * FROM `crowd_product` where c_status=1 and UNIX_TIMESTAMP(c_day)*1000<? and c_arrive<c_targetmoney LIMIT ?,?";
        dbhelp.query(suoyousql,params2,(err,reslut)=>{
          cb(err,reslut);
       })
      }
      

      setTimeout(()=>
      {
         async.parallel([fn1,fn2,fn3,fn4,fn5,fn6],(err,val)=>
         {
          //  console.log("val",val);
            let resultObj = {
               "code": 0,
               "msg": "",
               "count": val[1][0]["count1"],
               data: val[0],
               jjcrowd:val[2],
               suoyou:val[3],
               success:val[4],
               fail:val[5]
           }
           response.json(resultObj);
         })
      
      },1000)
})


adminRouter.post("/updatecrowdstatus", (request, response, next) => {
  let updatestatus_sql = "UPDATE `crowd_product` SET c_status=1 WHERE c_id=?";
  let params = [request.body.c_id];
  // console.log(params)
  dbhelp.query(updatestatus_sql, params, (err, reslut) => {
    console.log(reslut)
    if (err) {
      response.json({
        err
      })
    } else {
      console.log(reslut)
      if (reslut.affectedRows >= 1) {
        response.json({
          msg: "审核成功",
          status: 1,
        })
      } else {
        response.json({
          msg: "提交审核失败",
          status: -1
        })
      }
    }
  })
})


adminRouter.post("/updateremen", (request, response, next) => {

  let updateremen_sql = "UPDATE `crowd_product` SET c_remen=? WHERE c_id=?";
  let params = [request.body.c_remen,request.body.c_id];
  // console.log(params)
  dbhelp.query(updateremen_sql, params, (err, reslut) => {
    console.log(reslut)
    if (err) {
      response.json({
        err
      })
    } else {
      console.log(reslut)
      if (reslut.affectedRows >= 1) {
        response.json({
          msg: "修改成功",
          status: 1,
        })
      } else {
        response.json({
          msg: "修改失败",
          status: -1
        })
      }
    }
  })
})

adminRouter.post("/getorder",(request,response,next)=>
    {
        let params=[request.body.u_id];
        // console.log(request.body)
        let getordersql="SELECT * FROM `order`";
        dbhelp.query(getordersql,params,(err,result)=>
        {
            if(err)
            {
                response.json({
                    err
                })
            }
            else{
                // console.log(result.length);
                if(result.length==0)
                {
                    response.json({
                        msg:"还没有任何订单",
                        status:0
                    })
                }
                else{
                    response.json({
                        msg:"成功返回",
                        status:1,
                        result:result
                    })
                }
            }
        })
        
    })


    adminRouter.post("/cartmsg",(request,response,next)=>
{
   let size = request.body.limit * 1 // 页大小
   console.log(request.body.limit);
   let start = (request.body.page - 1) * request.body.limit; 
   let params=[start,size]
   console.log(params);
      function fn1(cb)
      {
         let getusersql="SELECT * FROM cart"
         
         console.log(request.body)
         if(request.body.name)
         {
            params.unshift(request.body.name);
            console.log(params)
            getusersql += " WHERE LOCATE(?, `u_name`)"
         }
         getusersql+=" LIMIT ?,? ;"
         console.log(getusersql);
         dbhelp.query(getusersql,params,(err,reslut)=>{
          console.log(getusersql);
            cb(err,reslut);
         }
         )
      }
      function fn2(cb)
      {
         let sqlcount="SELECT COUNT(*) AS count1  FROM cart";
         let params=[];
         if(request.body.name)
         {
            params.unshift(request.body.name);
            sqlcount += " WHERE LOCATE(?, `u_name`) ";
         }
         dbhelp.query(sqlcount,params,(err,result)=>
         {
            cb(err,result);
         })
      }

      setTimeout(()=>
      {
         async.parallel([fn1,fn2],(err,val)=>
         {
           console.log(val);
            let resultObj = {
               "code": 0,
               "msg": "",
               "count": val[1][0]["count1"],
               data: val[0]
           }
           response.json(resultObj);
         })
      
      },1000)
})

adminRouter.post("/addproduct",(request,response,next)=>
{
  
    let params=[request.body.p_name,request.body.p_img,request.body.p_price,request.body.p_stock,request.body.p_detailes,request.body.p_company,request.body.p_style,request.body.p_imgs,request.body.p_summary,request.body.p_problem,request.body.p_report];
  console.log(params);
    // console.log(request.body)
// color:red,bule,green,pink,purple,yellow
    let addproductsql="INSERT INTO `hs_product` (p_name,p_img,p_price,p_stock,p_detailes,p_company,p_style,p_imgs,p_summary,p_problem,p_report) VALUES (?,?,?,?,?,?,?,?,?,?,?)";
    dbhelp.query(addproductsql,params,(err,result)=>
    {
        if(err)
        {
            response.json({
                err
            })
        }
        else{
            // console.log(result);
            if(result.affectedRows>=1)
            {
                 response.json({
                     msg:"添加商品成功成功",
                     status:"success"
            })
            }
            else{
                response.json({
                    msg:"添加商品失败",
                    status:"warning"
                })
            }
           
        }
    })
    
}) 

module.exports = adminRouter;
